package com.youmingxing.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.R;
import com.youmingxing.activity.selfInfo.PersonalInfoActivity;
import com.youmingxing.bean.selfinfo.SearchUser;
import com.youmingxing.bean.selfinfo.SearchWork;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * @author evilyin(ChenZhixi)
 * @since 2015-9-4
 */

public class SearchActivity extends BaseActivity {
    ListView searchListView;
    List<SearchUser> mSearchUsers = new ArrayList<>();
    List<SearchWork> mSearchWorks = new ArrayList<>();
    private String keyword;
    private SearchAdapter adapter;

    private TextView mTextView;
    private View lineView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        final EditText searchEditText = (EditText) findViewById(R.id.search_edit_text);
        searchEditText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        TextView cancel = (TextView) findViewById(R.id.cancel);
        searchListView = (ListView) findViewById(R.id.search_list);
        mTextView = (TextView) findViewById(R.id.tv_search_info);
        lineView = findViewById(R.id.view);
        searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    showDialog("搜索中");
                    keyword = searchEditText.getText().toString();
                    mSearchUsers.clear();
                    mSearchWorks.clear();
                    AllStarApi.searchUserAndWork(keyword, initHandler);
                    return true;
                }
                return false;
            }
        });

        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 0 || position == mSearchUsers.size() + 1) {
                    return;
                }

                if (position == mSearchUsers.size()) {
                    Intent intent = new Intent(SearchActivity.this, SearchMoreUserActivity.class);
                    intent.putExtra("keyword", keyword);
                    startActivity(intent);
                    return;
                }

                if (position == mSearchUsers.size() + mSearchWorks.size() + 2) {
                    Intent intent = new Intent(SearchActivity.this, SearchMoreWorkActivity.class);
                    intent.putExtra("keyword", keyword);
                    startActivity(intent);
                    return;
                }

                if (position < mSearchUsers.size()) {
                    Intent intent = new Intent(SearchActivity.this, PersonalInfoActivity.class);
                    intent.putExtra("u_id", mSearchUsers.get(position).getId());
                    startActivity(intent);
                } else {
                    int location = mSearchUsers.size() + 2;
                    Intent intent = new Intent(SearchActivity.this, ContentDetailActivity.class);
                    intent.putExtra("content_id", mSearchWorks.get(position - location).getId());
                    startActivity(intent);
                }


            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        searchListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if (mSearchUsers != null && mSearchWorks != null) {
                    if (firstVisibleItem > mSearchUsers.size()) {
                        // 相关作品
                        mTextView.setText("相关作品");
                    } else {
                        // 用户昵称
                        mTextView.setText("用户昵称");
                    }
                }
            }
        });
    }

    BaseJsonHandler initHandler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
//            JSONArray data = response.optJSONArray("data");
            JSONObject userObject = response.optJSONObject("data").optJSONObject("users");
            JSONObject workObject = response.optJSONObject("data").optJSONObject("works");

            JSONArray userContent = userObject.optJSONArray("content");
            JSONArray workContent = workObject.optJSONArray("content");

            for (int i = 0; i < userContent.length(); i++) {
                JSONObject jsonObject = userContent.optJSONObject(i);
                SearchUser searchUser = new SearchUser();
                searchUser.setImg(jsonObject.optString("img"));
                searchUser.setId(jsonObject.optInt("id"));
                searchUser.setTitle(jsonObject.optString("title"));
                searchUser.setType(jsonObject.optInt("type"));
                searchUser.setTip(jsonObject.optString("tip"));
                mSearchUsers.add(searchUser);
            }
            for (int i = 0; i < workContent.length(); i++) {
                JSONObject jsonObject = workContent.optJSONObject(i);
                SearchWork searchWork = new SearchWork();
                searchWork.setImg(jsonObject.optString("img"));
                searchWork.setId(jsonObject.optInt("id"));
                searchWork.setTitle(jsonObject.optString("title"));
                searchWork.setType(jsonObject.optInt("type"));
                searchWork.setTip(jsonObject.optString("tip"));
                mSearchWorks.add(searchWork);
            }
            adapter = new SearchAdapter();
            searchListView.setAdapter(adapter);
            mTextView.setVisibility(View.VISIBLE);
            lineView.setVisibility(View.VISIBLE);
        }
    };


    private class ViewHolder {
        ImageView Image;
        TextView Name;
        TextView Info;
    }

    private class SearchAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mSearchUsers.size() + mSearchWorks.size() + 3;
        }

        @Override
        public Object getItem(int position) {
            if (position == mSearchUsers.size() || position == mSearchUsers.size() + 1
                    || position == mSearchUsers.size() + mSearchWorks.size() + 2) {
                return null;
            }
            if (position < mSearchUsers.size()) {
                // 把多出来的特殊条目减掉
                return mSearchUsers.get(position);
            } else {
                int location = mSearchUsers.size() + 2;
                return mSearchWorks.get(position - location);
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public android.view.View getView(int position, View convertView, ViewGroup parent) {
            if (position == mSearchUsers.size() + 1) {
                // 表示相关作品
                View view = View.inflate(SearchActivity.this, R.layout.item_special_search, null);
                return view;
            }
            if (position == mSearchUsers.size()) {
                View view = View.inflate(SearchActivity.this, R.layout.item_more_search, null);
                TextView textView = (TextView) view.findViewById(R.id.tv_search_more);
                textView.setText("查找更多选手");
                return view;
            }

            if (position == mSearchUsers.size() + mSearchWorks.size() + 2) {
                View view = View.inflate(SearchActivity.this, R.layout.item_more_search, null);
                TextView textView = (TextView) view.findViewById(R.id.tv_search_more);
                textView.setText("查找更多作品");
                return view;
            }
            ViewHolder holder;

            if (convertView != null && convertView instanceof RelativeLayout) {
                holder = (ViewHolder) convertView.getTag();
            } else {
                convertView = View.inflate(SearchActivity.this, R.layout.list_item_search, null);
                holder = new ViewHolder();
                holder.Image = (ImageView) convertView.findViewById(R.id.iv_image);
                holder.Name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.Info = (TextView) convertView.findViewById(R.id.tv_info);
                convertView.setTag(holder);
            }

            if (position < mSearchUsers.size()) {
                // 把多出来的特殊条目减掉
                SearchUser searchUser = mSearchUsers.get(position);
                Glide.with(SearchActivity.this).load(searchUser.getImg()).placeholder(R
                        .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder.Image);
                holder.Name.setText(searchUser.getTitle());
                holder.Info.setText(searchUser.getTip());

            } else {
                int location = mSearchUsers.size() + 2;
                SearchWork searchWork = mSearchWorks.get(position - location);
                System.out.println("searchWork = " + searchWork);
                Glide.with(SearchActivity.this).load(searchWork.getImg()).placeholder(R
                        .drawable.default_16_9).animate(R.anim.abc_fade_in).into(holder.Image);
                holder.Name.setText(searchWork.getTitle());
                holder.Info.setText(searchWork.getTip());
            }
            return convertView;
        }
    }
}
